package com.smkj.kaoqin.modules.common.service.impl;



import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smkj.kaoqin.common.constant.JwtClaimsConstant;
import com.smkj.kaoqin.common.enumeration.GlobalExceptionEnum;
import com.smkj.kaoqin.common.properties.JwtProperties;
import com.smkj.kaoqin.common.result.VResponse;
import com.smkj.kaoqin.common.utils.JwtUtil;
import com.smkj.kaoqin.modules.common.mapper.UserMapper;
import com.smkj.kaoqin.modules.common.pojo.db.User;
import com.smkj.kaoqin.modules.common.pojo.dto.UserLoginDTO;
import com.smkj.kaoqin.modules.common.service.IUserService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yztyear
 * @since 2024-09-11
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Resource
    private JwtProperties jwtProperties;
    @Override
    public VResponse<String> login(UserLoginDTO userLoginDTO) {
        // 查询该用户是否存在
        Long account = userLoginDTO.getAccount();
        String password = userLoginDTO.getPassword();
        User user = baseMapper.selectUserInfo(account);

        if (BeanUtil.isEmpty(user)) {
            return VResponse.result(GlobalExceptionEnum.ERROP_USER_PASSWORD);
        }

        //对前端传过来的明文密码进行md5加密处理
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if(!password.equals(user.getPassword())){
            return VResponse.result(GlobalExceptionEnum.ERROP_USER_PASSWORD);
        }

        // 清除用户隐私信息
        user.setPassword(null);
        user.setPhoneNumber(null);
//        String userInfo = JSON.toJSONString(user);
        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.Account,user.getAccount());
        String token = JwtUtil.createJWT(
                jwtProperties.getSecretKey(),
                jwtProperties.getTtl(),
                claims);

        return VResponse.success(200,"登录成功",token);
    }

    @Override
    public void register(UserLoginDTO userLoginDTO) {
        String password = userLoginDTO.getPassword();
        // md5加密密码
        userLoginDTO.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        User user = BeanUtil.copyProperties(userLoginDTO, User.class);
        baseMapper.insert(user);
    }
}

